package com.cl.utils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class CodeUtil {

    public static void getCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        int width = 100;
        int height = 35;
        //1.创建一对象，在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //2.美化图片
        //2.1 填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.white);//设置画笔颜色
        //图片坐标起始点是左上角
        g.fillRect(0,0,width,height);
        //2.2画边框
        g.setColor(Color.black);
        //width和height分别-1，为了边框右半部分有显示
        g.drawRect(0,0,width - 1,height - 1);
        //定义可以在页面上显示字符
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        //生成随机角标
        Random ran = new Random();
        char [] chars = new char[4];
        //验证码显示字符个数为4
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);//随机字符
            chars[i-1] = ch;
            //2.3写验证码
            //具体验证码显示位置定义
            g.drawString(ch+"",width/5*i,height/2);
        }
        session.setAttribute("verification",chars);
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
}
